package com.spring.pick2pick.dao;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.stereotype.Repository;

import com.spring.pick2pick.common.PageHandler;
import com.spring.pick2pick.model.FileInfo;
import com.spring.pick2pick.model.TeamItem;

/** 팀의 기능을 처리하는 Dao */
@Repository
public class TeamDao {
	
	@Autowired
	private SqlMapClientTemplate sqlMapClientTemplate;
	
	/** 팀 추가 기능 */
	public int addTeam(TeamItem item) {
		int idImage = (Integer) sqlMapClientTemplate.insert("common.addImage", item.getFinfo());
		item.setIdImage(idImage);
		return (Integer) sqlMapClientTemplate.insert("team.addTeam", item);
	}
	
	/** 팀 수정 기능 */
	public int editTeam(TeamItem item) {
		
		if (item.getFinfo() != null) {
			item.getFinfo().setIdImage(item.getIdImage());
			int idImage = item.getIdImage();
			FileInfo image = (FileInfo) sqlMapClientTemplate.queryForObject("common.getImage", idImage);
			
			File f = new File(image.getFileDir() + "/" + image.getFileSaveName());
			if (f.exists()) {
				f.delete();
			}
			String fileName = image.getFileSaveName().replace(".", "_80.");
			f = new File(image.getFileDir() + "/" + fileName);
			if (f.exists()) {
				f.delete();
			}
			
			sqlMapClientTemplate.update("common.editImage", item.getFinfo());
		}
		
		return (Integer) sqlMapClientTemplate.update("team.editTeam", item);
	}
	
	/** 팀 조회 기능 */
	public TeamItem getTeam(TeamItem item) {
		return (TeamItem) sqlMapClientTemplate.queryForObject("team.getTeam", item);
	}
	
	/** 팀 전시여부 기능 */
	public int editDisplay(TeamItem item) {
		return (Integer) sqlMapClientTemplate.update("team.editDisplay", item);
	}
	
	/** 활성 팀 카운트 */
	public int getDisplayCount(String where) {
		return (Integer) sqlMapClientTemplate.queryForObject("team.getDisplayCount", where);
	}
	
	/** 비활성 팀 카운트 */
	public int getUnDisplayCount(String where) {
		return (Integer) sqlMapClientTemplate.queryForObject("team.getUnDisplayCount", where);
	}
	
	/** 팀 리스트 기능 */
	@SuppressWarnings("unchecked")
	public List<TeamItem> getTeamList(int page, int size, String where, String order) {
		
		int total = (Integer) sqlMapClientTemplate.queryForObject("team.getTeamListCount", where);
		
		if (size == -1) {
			size = total;
		}
		
		if (total == 0) {
			PageHandler.freeInstance();
		} else {
			PageHandler.getInstance(page, total, size, 10);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", PageHandler.getInstance().getStartRec());
		map.put("end", PageHandler.getInstance().getPageArticleCount());
		map.put("where", where);
		map.put("order", order);
		
		List<TeamItem> list = sqlMapClientTemplate.queryForList("team.getTeamList", map);
		
		return list;
	}
	
}
